<template>
  <d2-container>
    <template>
      <d2-crud
        ref="d2Crud"
        selection-row
        @selection-change="handleSelectionChange"
        :columns="columns"
        :data="data"
        :loading="loading"
        :pagination="pagination"
        @pagination-current-change="paginationCurrentChange"
        @row-add="handleRowAdd"
      >
        <el-button size="mini" slot="header" style="margin-bottom: 5px" @click="addRow">新增</el-button>
        <el-button size="mini" slot="header" style="margin-bottom: 5px" @click="deleteRows">删除</el-button>
      </d2-crud>
    </template>
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="45%" top="10vh">
      <el-form
        :model="dialogForm.formData"
        ref="dialogForm"
        size="mini"
        style="margin-bottom: -18px;width:825px"
        :rules="rules"
        :inline-message="true"
      >
        <div class="dialogInfoBox">
          <div class="dialogInfoTitle">价格方案</div>
          <div class="dialogInfo">
            <el-form-item label="价格方案名称" prop="priceName" label-width="110px">
              <el-input
                v-model="dialogForm.formData.priceName"
                placeholder="请输入"
                style="width: 220px;"
              />
            </el-form-item>
            <el-form-item label="生效日期" prop="startdate" label-width="110px">
              <el-date-picker
                v-model="dialogForm.formData.startdate"
                style="width: 220px;"
                type="date"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
          </div>

          <div class="dialogInfo">
            <el-form-item label="启用状态" prop="state" label-width="110px">
              <el-select
                v-model="dialogForm.formData.state"
                placeholder="请选择"
                style="width: 220px;"
              >
                <el-option
                  v-for="(item, index) in dialogForm.selectOption.enabledState"
                  :key="index"
                  :label="item.valueName"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </div>
          <div class="dialogInfo">
            <el-form-item label="计费方式" prop="ladderType" label-width="110px">
              <el-select
                v-model="dialogForm.formData.ladderType"
                placeholder="请选择"
                style="width: 220px;"
              >
                <el-option
                  v-for="(item, index) in dialogForm.selectOption.priceTypeOption"
                  :key="index"
                  :label="item.valueName"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </div>
          <div class="dialogInfo" v-show="dialogForm.formData.ladderType=== 0">
            <el-form-item label="用能价格" prop="flatPrice" label-width="110px">
              <el-input-number
                v-model="dialogForm.formData.flatPrice"
                placeholder="请输入"
                style="width: 220px;"
                :min="0"
              ></el-input-number>
            </el-form-item>
          </div>
          <div class="dialogInfo" v-show="dialogForm.formData.ladderType=== 1">
            <el-form-item label="阶梯用量" label-width="110px">
              <i class="el-icon-circle-plus-outline plusBtn" @click="addLadderDosage"></i>
              <i class="el-icon-circle-close minusBtn" @click="deleteLadderDosage"></i>
            </el-form-item>
          </div>
          <div class="priceStageBox" v-show="dialogForm.formData.ladderType== 1">
            <div
              class="priceStage"
              v-for="(item, index) in dialogForm.formData.ladderDosage"
              :key="index"
            >
              <div>
                <el-form-item
                  :label="'阶梯'+ (index + 1)"
                  label-width="110px"
                  :prop="'ladderDosage.' + index + '.dosageStart'"
                  :rules="{
                    required: true, message: '必填', trigger: 'blur'
                }"
                >
                  <span>＞</span>
                  <el-input-number
                    v-model="item.dosageStart"
                    placeholder="请输入"
                    style="width: 100px;"
                    :min="0"
                    :disabled="true"
                  ></el-input-number>
                  <span>≤</span>

                  <el-input-number
                    v-model="item.dosageEnd"
                    placeholder="请输入"
                    style="width: 100px;"
                    :min="index != 0 ?dialogForm.formData.ladderDosage[index - 1].dosageEnd:0"
                    @change="getDosageEnd(item,index)"
                  ></el-input-number>
                </el-form-item>
              </div>

              <el-form-item
                label="阶梯金额"
                label-width="110px"
                :prop="'ladderDosage.' + index + '.addPrice'"
                :rules="{
                    required: true, message: '必填', trigger: 'blur'
                }"
              >
                <el-input-number
                  v-model="item.addPrice"
                  placeholder="请输入"
                  style="width: 220px;"
                  :min="0"
                >
                  <template slot="append">元</template>
                </el-input-number>
              </el-form-item>
            </div>
          </div>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="saveDialog('dialogForm')">确 定</el-button>
      </span>
    </el-dialog>
  </d2-container>
</template>

<script>
import util from "@/libs/util";
import { Divider } from "element-ui";

export default {
  name: "price",
  data() {
    return {
      dialogForm: {
        selectOption: {},
        formData: {
          flatPrice: "",
          id: "",
          ladderDosage: [
            { dosageStart: 0, dosageEnd: 10, addPrice: 0 },
            { dosageStart: 10, dosageEnd: 20, addPrice: 0 }
          ],
          priceName: "",
          startdate: "",
          state: "",
          ladderType:'',
        }
      },
      dialogTitle: "添加",
      dialogVisible: false,
      loading: false,
      pagination: {
        currentPage: 1,
        pageSize: 100,
        total: 0
      },
      columns: [
        {
          title: "序号",
          key: "serialNum",
          width: 50
        },
        {
          title: "价格方案名称",
          key: "priceName",
          sortable: true
        },
        {
          title: "生效日期",
          key: "startdate",
          sortable: true
        },
        {
          title: "用能价格",
          key: "flatPrice",
          sortable: true
        },
        {
          title: "启用状态",
          key: "stateName",
          sortable: true
        },
        {
          title: "操作",
          key: "",
          component: {
            render: (h, row, node, index) => {
              return (
                <div>
                  <button
                    class="el-button el-button--default el-button--mini"
                    onclick={() => {
                      this.handleDialogOpen(row);
                    }}
                  >
                    修改
                  </button>
                  <button
                    class="el-button el-button--danger el-button--mini"
                    onclick={() => {
                      this.handleRowRemove(row);
                    }}
                  >
                    删除
                  </button>
                </div>
              );
            }
          }
        }
      ],
      data: [],
      treeData: [],
      values: [],
      selectParams: {
        size: "mini"
      },
      selectionRow: [],
      formOptions: {
        labelWidth: "80px",
        labelPosition: "left",
        saveLoading: false
      },
      rules: {
        priceName: [{ required: true, message: "必填", trigger: "blur" }],
        startdate: [{ required: true, message: "必填", trigger: "blur" }],
        ladderType: [{ required: true, message: "必填", trigger: "blur" }],
        // dosage: [{ required: true, message: "必填", trigger: "blur" }],
        // addPrice: [{ required: true, message: "必填", trigger: "blur" }],
        state: [{ required: true, message: "必填", trigger: "blur" }]
      }
    };
  },
  mounted() {
    this.getEquipmentType();
    this.fetchData();
  },
  methods: {
    //获取dosage
    getDosageEnd(item, index) {
      for (
        let i = 0;
        i <= this.dialogForm.formData.ladderDosage.length - 1;
        i++
      ) {
        //修改index后的数据
        if (index < i) {
          //判断后一阶段的值是否等于前一阶段的开始值 并且不是最后一位
          if (index != this.dialogForm.formData.ladderDosage.length - 1) {
            this.dialogForm.formData.ladderDosage[i].dosageStart =
              item.dosageEnd;
            this.dialogForm.formData.ladderDosage[i].dosageEnd = item.dosageEnd;
          }
        }
      }
    },
    //关闭弹框
    handleClose() {
      this.dialogVisible = false;
    },
    //保存数据
    saveDialog(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let ladderDosageList = [];
          this.dialogForm.formData.ladderDosage.forEach(item=>{
            let ladderDosage = [];
            ladderDosage = [item.dosageStart,item.dosageEnd,item.addPrice],
            ladderDosageList.push(ladderDosage);
          })
          let saveObj = {
            flatPrice: this.dialogForm.formData.flatPrice,
            ladderDosage: JSON.stringify(ladderDosageList),
            priceName: this.dialogForm.formData.priceName,
            startdate: this.dialogForm.formData.startdate,
            state: this.dialogForm.formData.state,
            id: this.dialogForm.formData.id,
            ladderType:this.dialogForm.formData.ladderType,
          };
          console.log(saveObj);
          if (this.editFlag) {
            this.handleRowEdit(saveObj);
          } else {
            saveObj.id = "";
            this.handleRowAdd(saveObj);
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //删除阶梯用量
    deleteLadderDosage() {
      this.dialogForm.formData.ladderDosage.pop();
    },
    //添加阶梯用量
    addLadderDosage() {
      let addObj = {
        dosageStart: this.dialogForm.formData.ladderDosage[
          this.dialogForm.formData.ladderDosage.length - 1
        ].dosageEnd,
        dosageEnd: this.dialogForm.formData.ladderDosage[
          this.dialogForm.formData.ladderDosage.length - 1
        ].dosageEnd,
        addPrice: 0
      };
      this.dialogForm.formData.ladderDosage.push(addObj);
    },
    handleSelectionChange(selection) {
      this.selectionRow = selection;
    },
    deleteRows() {
      this.$confirm("确定删除吗?", "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error"
      }).then(() => {
        this.$api
          .admin_price_delete(this.selectionRow.map(item => item.id))
          .then(res => {
            this.$message({
              message: "删除成功",
              type: "success"
            });
            this.fetchData();
          });
      });
    },
    //删除row数据
    handleRowRemove(row) {
      this.$confirm("确定删除吗?", "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error"
      }).then(() => {
        this.$api.admin_price_delete([row.id]).then(res => {
          this.$message({
            message: "删除成功",
            type: "success"
          });
          this.fetchData();
        });
      });
    },
    handleDialogOpen(row) {
      this.dialogTitle = "修改-" + row.priceName;
      this.editFlag = true;
      this.dialogVisible = true;
      this.$api.admin_price_get({ id: row.id }).then(res => {
        let ladderDosageList = JSON.parse(res.ladderDosage);
        let ladderDosage = [];
        ladderDosageList.forEach(item=>{
          let dosageObj = {
            dosageStart : item[0],
            dosageEnd : item[1],
            addPrice : item[2],
          }
          ladderDosage.push(dosageObj);
        })
        res.ladderDosage = ladderDosage;
        this.dialogForm.formData = res;
      });
    },
    //增加row数据
    handleRowEdit(row) {
      this.formOptions.saveLoading = true;
      this.$api
        .admin_price_update(row)
        .then(res => {
          this.$message({
            message: "保存成功",
            type: "success"
          });
          this.handleFormSubmit();
          this.dialogVisible = false;
        })
        .finally(() => {
          this.formOptions.saveLoading = false;
        });
    },
    //新增数据
    addRow() {
      //修改状态
      this.editFlag = false;
      this.dialogVisible = true;
      this.dialogTitle = "添加";
      let templateObj = {};
      this.$refs.d2Crud.setFormData(templateObj);
    },
    handleRowAdd(row, done) {
      this.formOptions.saveLoading = true;
      this.$api
        .admin_price_add(row)
        .then(res => {
          this.$message({
            message: "保存成功",
            type: "success"
          });
          this.handleFormSubmit();
          this.dialogVisible = false;
        })
        .finally(() => {
          this.formOptions.saveLoading = false;
        });
    },
    //获取查询枚举
    getEquipmentType() {
      this.$api
        .admin_price_getEquipmentType()
        .then(res => {
          this.dialogForm.selectOption.enabledState = res.enabledState;
          this.dialogForm.selectOption.priceTypeOption = res.ladder;
        })
        .catch(err => {
          console.log("err", err);
        })
        .finally(() => {});
    },
    //分页操作
    paginationCurrentChange(currentPage) {
      this.pagination.currentPage = currentPage;
      this.fetchData();
    },
    onAreaChange(data, node) {
      this.queryForm.areaId = data.id;
      this.queryForm.areaName = data.name;
      this.fetchData();
    },
    fetchData() {
      this.loading = true;
      this.$api
        .admin_price_getPageList({
          pageNum: this.pagination.currentPage,
          pageSize: this.pagination.pageSize
        })
        .then(res => {
          this.data = res.data;
          this.pagination.total = res.total;
        })
        .catch(err => {
          console.log("err", err);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleFormSubmit() {
      this.pagination.currentPage = 1;
      this.fetchData();
    }
  }
};
</script>
<style lang="scss" scoped >
.dialogInfoBox {
  display: flex;
  flex-direction: column;
  margin-bottom: 10px;
  padding: 20px 10px 10px 10px;
  border: 1px #a3a3a3 solid;
  border-radius: 4px;
  width: 800px;
  position: relative;
  .dialogInfoTitle {
    position: absolute;
    top: -10px;
    background: #fff;
    padding: 0 5px;
    font-weight: bold;
  }
  .dialogInfo {
    width: 100%;
    display: flex;
    flex-direction: row;
    border-top: 1px #a3a3a3 solid;
    padding-top: 10px;
    & > div {
      width: 50%;
      margin-bottom: 10px;
    }
    .plusBtn {
      font-size: 24px;
      cursor: pointer;
      &:hover {
        color: green;
      }
    }
    .minusBtn {
      font-size: 24px;
      cursor: pointer;
      margin-left: 15px;
      &:hover {
        color: green;
      }
    }
  }
  .priceStageBox {
    width: 100%;
    .priceStage {
      width: 100%;
      display: flex;
      flex-direction: row;
      & > div {
        width: 50%;
      }
    }
  }
}
</style>
